<template>
  <div>
    <div class="backgroundfff" style="padding: 0 0.9375rem;">
      <p style="margin-top: 0.3125rem;padding-top: 0.625rem;">{{$t('dashbord.personal.uploadIdcard')}}</p>
      <van-row>
        <p style="color: red;">* 拍照时请保证身份证占满相框</p>
        <van-col :span="12" class="idCard">
          <img v-if="form.frontUrl" @click="bigAvatar(form.frontUrl)" :src="form.frontUrl" alt="">
          <div v-else>
            <van-loading type="spinner" color="#1989fa" vertical v-if="isLoadingFront">正在上传...</van-loading>
            <div v-else @click="onCaptureImage('front')">
              <van-icon name="photo-o" style="font-size: 1.875rem;" />
              <div style="padding: 0.9375rem 0;font-size: 0.75rem;">{{$t('dashbord.personal.uploadIdcardPositive')}}</div>
            </div>
          </div>
          <van-button v-if="form.frontUrl" size="mini" @click="reUpload('front')">重新上传</van-button>
        </van-col>
        <van-col :span="12" class="idCard">
          <img v-if="form.backUrl" @click="bigAvatar(form.backUrl)" :src="form.backUrl" alt="">
          <div v-else>
            <van-loading type="spinner" color="#1989fa" vertical v-if="isLoadingBack">正在上传...</van-loading>
            <div v-else @click="onCaptureImage('back')">
              <van-icon name="photo-o" style="font-size: 1.875rem;" />
              <div style="padding: 0.9375rem 0;font-size: 0.75rem;">{{$t('dashbord.personal.uploadIdcardReverse')}}</div>
            </div>
          </div>
          <van-button v-if="form.backUrl" size="mini" @click="reUpload('back')">重新上传</van-button>
        </van-col>
      </van-row>
    </div>
    <div v-if="showUser" class="marginTop5">
      <van-cell :title="$t('dashbord.personal.name')" :value="form.name" />
      <van-cell :title="$t('dashbord.personal.sex')" :value="form.gender" />
      <van-cell :title="$t('dashbord.personal.national')" :value="form.nation" />
      <van-cell :title="$t('dashbord.personal.birthday')" :value="form.birthday" />
      <van-cell :title="$t('dashbord.personal.idCard')" :value="form.idCardNo" />
      <van-field required name="uploader" label="上传头像">
        <template #input>
          <div v-if="form.headUrl" class="idCard">
            <img @click="bigAvatar(form.headUrl)" style="width: 100%;" :src="form.headUrl" alt="">
            <van-button size="mini" @click="reUpload('head')">重新上传</van-button>
          </div>
          <van-icon v-else name="photo-o" style="font-size: 1.875rem;" @click="uploadAvatar" />
        </template>
      </van-field>
      <van-field required name="radio" :label="$t('dashbord.personal.marriage')">
        <template #input>
          <van-radio-group v-model="form.marriage" direction="horizontal">
            <van-radio name="1">{{$t('dashbord.personal.unmarried')}}</van-radio>
            <van-radio name="2">{{$t('dashbord.personal.married')}}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
       <van-field
         required
         v-model="form.place"
         :name="$t('dashbord.personal.nativePlace')"
         :label="$t('dashbord.personal.nativePlace')"
         :placeholder="$t('dashbord.personal.nativePlace')"
       />
      <van-field
        required
        v-model="form.contact"
        :name="$t('dashbord.personal.emergencyContact')"
        :label="$t('dashbord.personal.emergencyContact')"
        :placeholder="$t('dashbord.personal.emergencyContact')"
      />
      <van-field
        required
        v-model="form.contactPhone"
        :name="$t('dashbord.personal.emergencyPhone')"
        :label="$t('dashbord.personal.emergencyPhone')"
        :placeholder="$t('dashbord.personal.emergencyPhone')"
      />
    </div>
    <div style="margin-top: 1.25rem;" class="center">
      <van-button style="width: 80%;" type="info" round @click="next">{{$t('dashbord.next')}}</van-button>
    </div>
  </div>
</template>

<script>
  import dashbordAPI from '../../../../api/dashbordAPI.js'
  import avatar from '@/assets/images/avatar.jpg'
  import {ImagePreview} from 'vant'
  import moment from 'moment'
  export default{
    data() {
      return {
        isLoadingBack: false,
        isLoadingFront: false,
        showUser: false,
        uploader: [],
        form: {
          name: '',
          idCardNo: '',
          gender: '',
          nation: '',
          frontUrl: '',
          backUrl: '',
          birthday: '',
          place: '',
          marriage: '',
          contact: '',
          contactPhone: '',
          headUrl: '',
          expireDate:　''
        }
      }
    },
    mounted() {
      let form = JSON.parse(localStorage.getItem('form'))
      if (form) {
        this.showUser = true
        this.form = form
      }
    },
    methods: {
      onCaptureImage(data) {
        if (data === 'back') {
          if (this.form.frontUrl) {
            let cmr = plus.camera.getCamera(1)
            let res = cmr.supportedImageResolutions[0]
            let fmt = cmr.supportedImageFormats[0]
            let _this = this
            cmr.captureImage(( path ) =>{
              plus.io.resolveLocalFileSystemURL(path,(entry)=>{
                if(entry.isFile){
                  entry.file((file) => {
                    if (file.size > 1024 * 1024) {
                      var pathCompress = "_doc/" + moment(new Date()) + ' ' + Math.random() + ".jpg";
                      plus.nativeUI.showWaiting("压缩图片")
                      plus.zip.compressImage({
                          src: file.fullPath,
                          dst: pathCompress
                        }, function(i) {
                          plus.nativeUI.closeWaiting()
                          file.fullPath = i.target
                          file.size = i.size
                          file.name = moment(new Date()) + '.jpg'
                          var fileReader = new plus.io.FileReader()
                          fileReader.readAsDataURL(file);
                          fileReader.onloadend = function(e){
                            let f = _this.dataURLtoFile(e.target.result.toString(),entry.name)
                            if (data === 'front') {
                              _this.isLoadingFront = true
                              dashbordAPI.uploadIdCard(f, data).then(res => {
                                _this.isLoadingFront = false
                                _this.form = res
                                _this.form.birthday = res.idCardNo.substr(6, 4) + '.' + res.idCardNo.substr(10, 2) + '.' + res.idCardNo.substr(12, 2)
                              }).catch(err => {
                                _this.isLoadingFront = false
                              }).finally(() => {
                                _this.isLoadingFront = false
                              })
                            } else {
                              _this.isLoadingBack = true
                              dashbordAPI.uploadIdCard(f, data).then(res => {
                                _this.isLoadingBack = false
                                _this.form.backUrl = res.backUrl
                                _this.form.expireDate = res.expireDate
                                if (res.expireDate && _this.form.name) {
                                  _this.showUser = true
                                }
                              }).catch(err => {
                                _this.isLoadingBack = false
                              }).finally(() => {
                                _this.isLoadingBack = false
                              })
                            }
                          }
                        },function(error) {
                          plus.nativeUI.closeWaiting()
                          console.log(error);
                      })
                    } else {
                      var fileReader = new plus.io.FileReader()
                      fileReader.readAsDataURL(file);
                      fileReader.onloadend = function(e){
                        let f = _this.dataURLtoFile(e.target.result.toString(),entry.name)
                        if (data === 'front') {
                          _this.isLoadingFront = true
                          dashbordAPI.uploadIdCard(f, data).then(res => {
                            _this.isLoadingFront = false
                            _this.form = res
                            _this.form.birthday = res.idCardNo.substr(6, 4) + '.' + res.idCardNo.substr(10, 2) + '.' + res.idCardNo.substr(12, 2)
                          }).catch(err => {
                            _this.isLoadingFront = false
                          }).finally(() => {
                            _this.isLoadingFront = false
                          })
                        } else {
                          _this.isLoadingBack = true
                          dashbordAPI.uploadIdCard(f, data).then(res => {
                            _this.isLoadingBack = false
                            _this.form.backUrl = res.backUrl
                            _this.form.expireDate = res.expireDate
                            if (res.expireDate && _this.form.name) {
                              _this.showUser = true
                            }
                          }).catch(err => {
                            _this.isLoadingBack = false
                          }).finally(() => {
                            _this.isLoadingBack = false
                          })
                        }
                      }
                    }
                  },(error) => {
                    console.log(error.message)
                  })
                }
              },(error)=>{
                console.log(error.message)
              })
            },( error ) => {
              console.log(error.message)
            },{
              resolution:res,
              format:fmt,
              optimize: false
            })
          } else {
            this.$toast('请等待正面照片上传完成...')
          }
        } else {
          let cmr = plus.camera.getCamera(1)
          let res = cmr.supportedImageResolutions[0]
          let fmt = cmr.supportedImageFormats[0]
          let _this = this
          cmr.captureImage(( path ) =>{
            plus.io.resolveLocalFileSystemURL(path,(entry)=>{
              if(entry.isFile){
                entry.file((file) => {
                  if (file.size > 1024 * 1024) {
                    var pathCompress = "_doc/" + moment(new Date()) + ' ' + Math.random() + ".jpg";
                    plus.nativeUI.showWaiting("压缩图片")
                    plus.zip.compressImage({
                        src: file.fullPath,
                        dst: pathCompress
                      }, function(i) {
                        plus.nativeUI.closeWaiting()
                        file.fullPath = i.target
                        file.size = i.size
                        file.name = moment(new Date()) + '.jpg'
                        var fileReader = new plus.io.FileReader()
                        fileReader.readAsDataURL(file);
                        fileReader.onloadend = function(e){
                          let f = _this.dataURLtoFile(e.target.result.toString(),entry.name)
                          if (data === 'front') {
                            _this.isLoadingFront = true
                            dashbordAPI.uploadIdCard(f, data).then(res => {
                              _this.isLoadingFront = false
                              _this.form = res
                              _this.form.birthday = res.idCardNo.substr(6, 4) + '.' + res.idCardNo.substr(10, 2) + '.' + res.idCardNo.substr(12, 2)
                            }).catch(err => {
                              _this.isLoadingFront = false
                            }).finally(() => {
                              _this.isLoadingFront = false
                            })
                          } else {
                            _this.isLoadingBack = true
                            dashbordAPI.uploadIdCard(f, data).then(res => {
                              _this.isLoadingBack = false
                              _this.form.backUrl = res.backUrl
                              _this.form.expireDate = res.expireDate
                              if (res.expireDate && _this.form.name) {
                                _this.showUser = true
                              }
                            }).catch(err => {
                              _this.isLoadingBack = false
                            }).finally(() => {
                              _this.isLoadingBack = false
                            })
                          }
                        }
                      },function(error) {
                        plus.nativeUI.closeWaiting()
                        console.log(error);
                    });
                  } else {
                    var fileReader = new plus.io.FileReader()
                    fileReader.readAsDataURL(file);
                    fileReader.onloadend = function(e){
                      let f = _this.dataURLtoFile(e.target.result.toString(),entry.name)
                      if (data === 'front') {
                        _this.isLoadingFront = true
                        dashbordAPI.uploadIdCard(f, data).then(res => {
                          _this.isLoadingFront = false
                          _this.form = res
                          _this.form.birthday = res.idCardNo.substr(6, 4) + '.' + res.idCardNo.substr(10, 2) + '.' + res.idCardNo.substr(12, 2)
                        }).catch(err => {
                          _this.isLoadingFront = false
                        }).finally(() => {
                          _this.isLoadingFront = false
                        })
                      } else {
                        _this.isLoadingBack = true
                        dashbordAPI.uploadIdCard(f, data).then(res => {
                          _this.isLoadingBack = false
                          _this.form.backUrl = res.backUrl
                          _this.form.expireDate = res.expireDate
                          if (res.expireDate && _this.form.name) {
                            _this.showUser = true
                          }
                        }).catch(err => {
                          _this.isLoadingBack = false
                        }).finally(() => {
                          _this.isLoadingBack = false
                        })
                      }
                    }
                  }
                },(error) => {
                  console.log(error.message)
                })
              }
            },(error)=>{
              console.log(error.message)
            })
          },( error ) => {
            console.log(error.message)
          },{
            resolution:res,
            format:fmt,
            optimize: false
          })
        }
      },
      dataURLtoFile(dataurl, filename) {//将base64转换为文件
          var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
              bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
          while(n--){
              u8arr[n] = bstr.charCodeAt(n);
          }
          return new File([u8arr], filename, {type:mime});
      },
      // 重新上传
      reUpload(data) {
        if (data === 'front') {
          this.form.frontUrl = ''
        } else if (data === 'head') {
          this.form.headUrl = ''
        } else {
          this.form.backUrl = ''
        }
      },
      // 上传身份证正面照片
      frontRead(file) {
        dashbordAPI.uploadIdCard(file.file, 'front').then(res => {
          this.form = res
          this.form.birthday = res.idCardNo.substr(6, 4) + '.' + res.idCardNo.substr(10, 2) + '.' + res.idCardNo.substr(12, 2)
        })
      },
      // 上传身份证反面照片
      backRead(file) {
        dashbordAPI.uploadIdCard(file.file, 'back').then(res => {
          this.form.backUrl = res.backUrl
          this.form.expireDate = res.expireDate
          if (res.expireDate && this.form.name) {
            this.showUser = true
          }
        })
      },
      uploadAvatar() {
        localStorage.setItem('form', JSON.stringify(this.form))
        this.$router.push({
          name: 'Camera'
        })
      },
      // 放大图片
      bigAvatar(img) {
        ImagePreview({
           images: [img],
        })
      },
      // 下一步
      next() {
        let form = JSON.parse(JSON.stringify(this.form))
        if (this.form.gender === '女') {
          form.gender = 2
        } else {
          form.gender = 1
        }
        form.marriage = parseInt(this.form.marriage)
        form.birthday = moment(this.form.birthday).format('yyyy-MM-DD')
        if (this.form.expireDate === '长期') {
          form.expireDate = this.form.expireDate
        } else {
          form.expireDate = moment(this.form.expireDate).format('yyyy-MM-DD')
        }
        if (form.frontUrl === '') {
          this.$toast.fail('请上传身份证正面照片');
          return;
        }
        if (form.backUrl === '') {
          this.$toast.fail('请上传身份证反面照片');
          return;
        }
        if (form.frontUrl !== '' && form.idCardNo !== '') {
          if (!this.form.headUrl) {
            this.$toast.fail('请上传头像');
            return;
          }
          if (!form.marriage) {
            this.$toast.fail('请选择婚姻状态');
            return;
          }
          if (!form.place) {
            this.$toast.fail('籍贯信息不能为空');
            return;
          }
          if (form.contact === '') {
            this.$toast.fail('紧急联系人不能为空');
            return;
          }
          if (form.contactPhone === '') {
            this.$toast.fail('紧急联系人电话不能为空');
            return;
          }
          let rule = /^1[3456789]\d{9}$/
          if (!rule.test(form.contactPhone)) {
            this.$toast.fail('请输入正确的紧急联系人电话');
            return;
          }
        }
        let projectId = localStorage.getItem('projectId')
        dashbordAPI.personSubmit(projectId, form).then(res => {
          localStorage.removeItem('form');
          this.$emit('next', {
            next: 0,
            id: res.id
          })
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .idCard{
    position: relative;
    text-align: center;
    padding: 0.3125rem;
    /deep/ .van-uploader{
      .van-uploader__upload{
        height: 6.25rem!important;
        .van-uploader__upload-icon{
          font-size: 3.125rem!important;
        }
      }
     }
    img{
      width: 100%;
    }
    svg{
      margin-top: 1.875rem;
    }
    /deep/ .van-uploader{
      width: 100%;
      .van-uploader__upload{
        margin: 0;
        background-color: inherit;
        width: 100%;
        height: 11.25rem;
        .van-uploader__upload-icon{
          font-size: 6.25rem;
        }
      }
    }
    .van-button{
      position: absolute;
      bottom: 0.9375rem;
      right: 0.625rem;
    }
  }
  .avatar{
    /deep/ .van-uploader{
      width: 100%;
      .van-uploader__upload{
        width: 100%;
        height: 8.125rem;
        margin: 0;
        .van-uploader__upload-icon{
          font-size: 2.5rem;
        }
      }
    }
  }
</style>
